 <template>
   <div class="search-container">
     <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
     <form action="/">
       <van-search
         v-model="searchText"
         show-action
         placeholder="请输入搜索关键词"
         background="#3296fa"
         @search="onSearch"
         @cancel="onCancel"
          @focus="isResultShow = false"
       />
     </form> 
     <!-- 1 搜索结果 在模板中判断是否绑定条件渲染 -->
         <search-result v-if="isResultShow"  :search-text="searchText"></search-result>
   <search-suggestion @search="onSearch" v-else-if="searchText"  :search-text="searchText">  </search-suggestion>
       <!-- 如果searchText没有值 判断联想建议 -->
    <search-history v-else :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"  @search="onSearch"></search-history>
    
   </div>
 </template>
 
 <script>
    import searchHistory from './components/search-history.vue'
   import searchSuggestion from './components/search-suggestion.vue'
   import searchResult from './components/search-result.vue'
import { setItem,getItem } from '@/utlis/storage'
 export default {
   name: 'SearchIndex',
   data() {
     return {
       searchText: '',
       isResultShow: false,
       searchHistories:getItem('TOUTIAO_SEARCH_HISTORY') || [] //储存的是历史记录数据
       
     }
  },
  watch: {
    //同步到本地存储
    searchHistories(value) {
                  //名称                  值
      setItem('TOUTIAO_SEARCH_HISTORY', value)
    }
   },
  methods: {
    // 确定搜索时触发
     onSearch(val) {
       this.searchText = val   // 更新文本框的内容

        //储存搜索历史记录
        //条件：不要又重复历史记录，最新的排在最前面
        const index =this.searchHistories.indexOf(val) 
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
            
          }
        this.searchHistories.unshift(val)
       this.isResultShow = true
     },
     onCancel() {
       this.$router.back()
     }
    },
   components: {
       searchHistory,
       searchSuggestion,
       searchResult
     }
 }
 </script>
 
 <style scoped lang="less">
 .search-container {
   .van-search__action {
     color: #fff;
   }
 }
 </style>
 